#!/usr/bin/python
# -*- coding: utf-8 -*-
# simple backup script
# copy all files and directories in dst_dir into a time stamped directory in dst_dir. if keep_backups != 0, delete all, but last <keep_backups> backup copies. this is done before backup copy, so we will end with keep_backups+1 copies.

import shutil
import os
import datetime
#from Tkinter import *
#import tkMessageBox
#import threading

# source and destination directories
src_dirs = [r"C:\daten", r"C:\Dokumente und Einstellungen"]
dst_dir  = "f:"
keep_backups    = 10

def win_copy(src, dst):
    cmd =  r'xcopy "%s" "%s\" /S /E /C /I /H /Y /F'%(src, dst)
    print cmd
    os.system(cmd)

def generic_copy(src, dst):
    import shutil
    print "copy %s => %s"%(src, dst)
    shutil.copytree(src, dst)

copy = generic_copy
if os.name == "nt":
    print "we are on a windows system"
    copy = win_copy

# expanduser
dst_dir = os.path.expanduser(dst_dir)
src_dirs = map(os.path.expanduser, src_dirs)
# normalize
dst_dir  = os.path.normpath(dst_dir)
src_dirs = map(os.path.normpath, src_dirs)
print "src:", src_dirs, "dst:", dst_dir

def delete_old_backups(dst_dir, keep_backups):
    # delete old backups
    assert keep_backups != 0
    # if gui: action.set("deleting old backups")
    backups = os.listdir(dst_dir)
    if len(backups) > keep_backups:
        backups.sort
        for dir in backups[:len(backups) - keep_backups]:
            print "deleting:", os.path.join(dst_dir, dir)
            shutil.rmtree(os.path.join(dst_dir, dir))
    backups = os.listdir(dst_dir)
    print "keeping:", backups
    
def make_backup_copy(src_dirs, dst_dir):
    # set up correct destination dir
    now = datetime.datetime.now()
    dst_dir += os.sep + "backup-%4i-%02i-%02i"%(now.year, now.month, now.day)
    dst_dir += "_%02i-%02i-%02i"%(now.hour, now.minute, now.second)
    os.mkdir(dst_dir)

    # make backup copy
    for src in src_dirs:
        dst = os.path.join(dst_dir, os.path.basename(src))
        copy(src, dst)
        
def main():
    start = datetime.datetime.now()
    
    delete_old_backups(dst_dir, keep_backups)
    make_backup_copy(src_dirs, dst_dir)
    
    print "Das Backup dauerte:", datetime.datetime.now() - start
    raw_input("press enter to quit")

if __name__ == '__main__':
    main()
